
const { ccclass, property } = cc._decorator;
// const gfx = cc['gfx'];

// const vertexFmt = new gfx.VertexFormat([
//     { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 },
//     { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
//     { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 4, normalize: true },
// ])
@ccclass
export default class simulateBookAssembler extends cc.Assembler {

    floatsPerVert = 5;

    uvOffset = 2;
    colorOffset = 4;

    public _renderData: cc.RenderData = null;
    public _local: Array<any> = [];
    public vertexes: Array<cc.Vec2> = [];

    // 模拟书本的顶点是按排数来定的，排数越多，效果越精细，一排有上下两个顶点每四个顶点渲染出两个三角形
    // 顶点排数
    _verticalCount = 8;
    get verticalCount() {
        return this._verticalCount;
    }
    set verticalCount(v) {
        if (v > 2) {
            this._verticalCount = v;
        }
    }

    get vertexesCount() {
        return this.verticalCount * 2;
    }
    // 索引个数等于 (排数-1)* 6
    get indicesCount() {
        return (this.verticalCount - 1) * 6;
    }

    get verticesFloats() {
        return this.floatsPerVert * this.vertexesCount;
    }

    init(comp: cc.Sprite) {
        super.init(comp);
        this._verticalCount = comp['_verticalCount'];
        this._renderData = new cc.RenderData();
        this._renderData.init(this);

        this.initLocal();
        this.initData();
    }

    initLocal() {
        this._local = [];
        this._local.length = this.vertexesCount;
    }
    initData() {
        let data = this._renderData;
        data.createFlexData(0, this.verticesFloats, this.indicesCount)

        // createFlexData不会填充顶点索引信息，手动补充一下
        let indices = data.iDatas[0];
        let count = this._verticalCount - 1;
        let offset = this._verticalCount;
        for (let i = 0, idx = 0; i < count; i++) {
            indices[idx++] = i + 0;
            indices[idx++] = i + 1;
            indices[idx++] = i + 0 + offset;

            indices[idx++] = i + 1;
            indices[idx++] = i + 0 + offset;
            indices[idx++] = i + 1 + offset;
        }
    }
    // getVfmt() {
    //     return vertexFmt;
    // }
    getBuffer() {
        //@ts-ignore
        return cc.renderer._handle._meshBuffer;
    }

    updateRenderData(sprite) {
        if (!sprite._spriteFrame) return;
        // this.packToDynamicAtlas(sprite, sprite._spriteFrame);

        if (sprite._vertsDirty) {
            this.updateVerts(sprite);
            // this.updateUVs(sprite);
            // this.updateColor(sprite);
            sprite._vertsDirty = false;
        }
    }

    // 将准备好的顶点数据填充进 VertexBuffer 和 IndiceBuffer
    fillBuffers(comp, renderer) {
        if (renderer.worldMatDirty) {
            this.updateWorldVerts(comp);
        }

        let renderData = this._renderData;
        let vData = renderData.vDatas[0];
        let iData = renderData.iDatas[0];

        let buffer = this.getBuffer(/*renderer*/);
        let offsetInfo = buffer.request(this.vertexesCount, this.indicesCount);

        // buffer data may be realloc, need get reference after request.

        // fill vertices
        let vertexOffset = offsetInfo.byteOffset >> 2,
            vbuf = buffer._vData;

        if (vData.length + vertexOffset > vbuf.length) {
            vbuf.set(vData.subarray(0, vbuf.length - vertexOffset), vertexOffset);
        } else {
            vbuf.set(vData, vertexOffset);
        }

        // fill indices
        let ibuf = buffer._iData,
            indiceOffset = offsetInfo.indiceOffset,
            vertexId = offsetInfo.vertexOffset;             // vertexId是已经在buffer里的顶点数，也是当前顶点序号的基数
        for (let i = 0, l = iData.length; i < l; i++) {
            ibuf[indiceOffset++] = vertexId + iData[i];
        }
    }

    updateColor(comp, color = null) {
        // render data = verts = x|y|u|v|color|x|y|u|v|color|...
        // 填充render data中4个顶点的color部分
        let uintVerts = this._renderData.uintVDatas[0];
        if (!uintVerts) return;
        color = color != null ? color : comp.node.color._val;
        let floatsPerVert = this.floatsPerVert;
        let colorOffset = this.colorOffset;
        for (let i = colorOffset, l = uintVerts.length; i < l; i += floatsPerVert) {
            uintVerts[i] = color;
        }
    }


    endPoint: cc.Vec2 = null;
    _bookPercent: number = 0;
    get bookPercent() {
        return this._bookPercent;
    }
    set bookPercent(v) {
        if (v >= 0 && v <= 1) {
            this._bookPercent = v;
        }
    }

    ctx: cc.Graphics = null;
    updateVerts(sprite) {
        let pointList = sprite.getVerts();
        // console.log(pointList)
        // debugger;
        let node = sprite.node,
            cw = node.width, ch = node.height;
        /******************uv计算所需参数 *************************/
        let uvs = sprite.spriteFrame.uv;
        let l = uvs[0],
            b = uvs[1],
            r = uvs[6],
            t = uvs[7]
            ;

        let uv = [l, t, r, t, r, b, l, b];
        if (sprite.spriteFrame.isRotated()) {
            uv = [r, b, r, t, l, t, l, b];
            // uv = [mx, my, l, b, l, t, r, t, r, b];
        }
        // let uv = [0.5, 0.5, 0, 1, 1, 1, 1, 0, 0, 0];
        let uvOffset = this.uvOffset;
        let floatsPerVert = this.floatsPerVert;
        let verts = this._renderData.vDatas[0];
        /******************************************************* */

        let local = this._local;

        let vertPercent = 0;
        let vertWidth = 0;
        let normalDistance = cw / (this.verticalCount - 1);

        // let ctx = GameHelper.getDebugSceneCtx();
        // ctx.clear();
        for (let i = 0; i < this.verticalCount; i++) {
            let point = pointList[i];
            let topOffset = i;
            let bottomOffset = (i + this.verticalCount);
            // debugger
            local[topOffset] = point.add(cc.v2(0, ch / 2));
            local[bottomOffset] = point.add(cc.v2(0, -ch / 2));

            // if (CC_PREVIEW) {
            //     let ctrlWpos = sprite.node.convertToWorldSpaceAR(local[topOffset]);
            //     let ctrl2Wpos = sprite.node.convertToWorldSpaceAR(local[bottomOffset]);
            //     // ctx.fillColor = cc.color(255, 255, 255);
            //     // ctx.circle(wpos.x, wpos.y, 5)
            //     // ctx.stroke();
            //     // ctx.fill();
            //     ctx.fillColor = cc.color(255, 0, 0);
            //     ctx.circle(ctrlWpos.x, ctrlWpos.y, 5)
            //     ctx.circle(ctrl2Wpos.x, ctrl2Wpos.y, 5)
            //     ctx.stroke();
            //     ctx.fill();
            // }

            if (i > 0) {
                // 叠加每一个点之间的距离来获取百分比
                vertWidth += pointList[i].sub(pointList[i - 1]).mag();
            }
            // 这里可以通过计算顶点之间的距离顺便更新uv
            let dstUVOffset = floatsPerVert * i + uvOffset;
            let secUVOffset = floatsPerVert * (i + this.verticalCount) + uvOffset;
            vertPercent = vertWidth / cw;
            verts[dstUVOffset] = l + (r - l) * vertPercent;
            verts[dstUVOffset + 1] = t;
            verts[secUVOffset] = l + (r - l) * vertPercent;
            verts[secUVOffset + 1] = b;
        }

        this.updateWorldVerts(sprite);
    }

    updateWorldVerts(comp) {
        if (CC_NATIVERENDERER) {
            this.updateWorldVertsNative(comp);
        } else {
            this.updateWorldVertsWebGL(comp);
        }
    }

    updateWorldVertsWebGL(comp) {
        let local = this._local;
        let verts = this._renderData.vDatas[0];

        let node = comp.node,
            cw = node.width, ch = node.height;
        // let appx = cw * (0.5 - node.anchorX);
        // let appy = ch * (0.5 - node.anchorY);

        let matrix = comp.node._worldMatrix;
        // cocos矩阵
        let matrixm = matrix.m,
            a = matrixm[0], b = matrixm[1], c = matrixm[4], d = matrixm[5],
            tx = matrixm[12], ty = matrixm[13];

        /*
        m00 = 1, m01 = 0, m02 = 0, m03 = 0,
        m04 = 0, m05 = 1, m06 = 0, m07 = 0,
        m08 = 0, m09 = 0, m10 = 1, m11 = 0,
        m12 = 0, m13 = 0, m14 = 0, m15 = 1
        */
        // [a,b,c,d] = _worldMatrix[1,2,4,5] == [1,0,0,1]
        // _worldMatrix[12,13]是xy的平移量
        // 即世界矩阵的左上角2x2是单元矩阵，说明在2D场景内没有出现旋转或者缩放
        let justTranslate = a === 1 && b === 0 && c === 0 && d === 1;
        let angle = node.angle;
        // CC_EDITOR && Editor.log('angle', angle);
        // let radian = angle * Math.PI / 180
        // 实现矩阵
        // a = Math.cos(radian) * node.scaleX;
        // b = Math.sin(radian);
        // c = -Math.sin(radian);
        // d = Math.cos(radian) * node.scaleY;
        // render data = verts = x|y|u|v|color|x|y|u|v|color|...
        // 填充render data中4个顶点的xy部分
        let index = 0;
        let floatsPerVert = this.floatsPerVert;
        for (let i = 0; i < local.length; i++) {
            let p = local[i];
            verts[index] = p.x * a + p.y * c + tx;
            verts[index + 1] = p.x * b + p.y * d + ty;
            index += floatsPerVert;
        }
    }

    // native场景下使用的updateWorldVerts
    // copy from \jsb-adapter-master\engine\assemblers\assembler-2d.js
    updateWorldVertsNative(comp) {
        let local = this._local;
        let verts = this._renderData.vDatas[0];
        let floatsPerVert = this.floatsPerVert;
        let node = comp.node,
            cw = node.width, ch = node.height;
        // let appx = cw * (0.5 - node.anchorX);
        // let appy = ch * (0.5 - node.anchorY);

        let index: number = 0;
        for (let i = 0; i < local.length; i++) {
            let p = local[i];
            verts[index] = p.x;
            verts[index + 1] = p.y;
            index += floatsPerVert;
        }
    }

    packToDynamicAtlas(comp, frame) {
        if (CC_TEST) return;

        if (!frame._original && cc.dynamicAtlasManager && frame._texture.packable) {
            let packedFrame = cc.dynamicAtlasManager.insertSpriteFrame(frame);
            //@ts-ignore
            if (packedFrame) {
                frame._setDynamicAtlasFrame(packedFrame);
            }
        }
        let material = comp._materials[0];
        if (!material) return;

        if (material.getProperty('texture') !== frame._texture) {
            // texture was packed to dynamic atlas, should update uvs
            comp._vertsDirty = true;
            comp._activateMaterial();
        }
    }
}
